from .models import User

def hasUser(username:str)->bool:
    return User.objects.filter(username=username).exists()

def getUserByName(username:str)->User|None:
    '''通过用户名获取用户对象'''
    return User.objects.filter(username=username).first()

def getUserByID(userid:int)->User|None:
    '''通过 ID 获取用户对象'''
    return User.objects.filter(id=userid).first()

from .um_exceptions import *

def loginUser(userid:int,password:str)->str:
    '''登录用户，如果失败，返回 None'''
    user=getUserByID(userid)
    if user is None:
        raise UserNotFound # failed, user not found
    if user.check_password(password)==False:
        raise InvalidCred # failed, invalid login token
    if user.is_banned==True:
        raise UserIsBanned
    user.clear_session_token()
    return user.generate_session_token()

def getIDByName(username:str)->int:
    user=getUserByName(username)
    if user is None:
        raise UserNotFound
    return user.id

def logoutUser(userid:int,token:str):
    '''登出用户'''
    user=getUserByID(userid)
    if user is None:
        raise UserNotFound
    if user.session_token=="":
        raise UserNotLogin
    if user.session_token!=token:
        raise InvalidCred # you cannot logout other's account,otherwise you have the token
    user.clear_session_token()

def checkToken(userid:int,token:str)->bool:
    '''鉴权，不成功不会抛出错误
       我现在还不需要权限组，应该吧。
    '''
    user=getUserByID(userid)
    if user is None:
        return False
    if user.session_token=="": # not loged in
        return False
    if user.session_token!=token:
        return False
    if user.is_banned:
        return False
    return True

def registerUser(username:str,password:str):
    '''注册'''
    if hasUser(username):
        raise UserExisted
    user=User(username=username)
    user.set_password(password)
    user.save()
    user.clear_session_token()